import { currentColorScheme } from "@/colorscheme/colorscheme";
import { Connection } from "jsplumb";
import { StatusManager } from "./statusmgr";
import { parseMidpointUUID } from "./utils";

interface FlowchartComponent {
    statusMgr: StatusManager,
}

// 点击一个Connector，添加一个拐点。
export const onEdgeClick = (fc: FlowchartComponent, conn: Connection, e: Event): void => {
    const evt = e as MouseEvent;
    const startElemID: string = (conn.endpoints[0] as any).elementId; // 如果前驱节点是奇数号或者端口，则其为横向；。

    const endElemID: string = (conn.endpoints[1] as any).elementId;
    const positions: {
        startLeft: number;
        startTop: number;
        endLeft: number;
        endTop: number;
    } = { startLeft: -1, startTop: -1, endLeft: -1, endTop: -1 };
    let edgePos: "vertical" | "horizontal" = "horizontal";

    let previousIndex = -2;
    if (!startElemID.startsWith("midpoint")) {
        const endpointUUID = (conn.endpoints[0] as any).getUuid();
        const { left, top } =
            fc.statusMgr.getEndpointPosition(endpointUUID);
        positions.startLeft = left;
        positions.startTop = top;
        edgePos = "horizontal";
        previousIndex = -1;
    } else {
        const { left, top } = fc.statusMgr.getMidpointPos(startElemID);
        const midpointIndex = parseMidpointUUID(startElemID).index;
        positions.startLeft = left;
        positions.startTop = top;
        if (midpointIndex % 2 == 1) {
            edgePos = "horizontal";
        } else {
            edgePos = "vertical";
        }
        previousIndex = midpointIndex;
    }
    if (!endElemID.startsWith("midpoint")) {
        const endpointUUID = (conn.endpoints[1] as any).getUuid();
        const { left, top } =
            fc.statusMgr.getEndpointPosition(endpointUUID);
        positions.endLeft = left;
        positions.endTop = top;
    } else {
        const { left, top } = fc.statusMgr.getMidpointPos(endElemID);
        positions.endLeft = left;
        positions.endTop = top;
    }
    const edge = fc.statusMgr.queryEdgeofConnection(conn);

    fc.statusMgr.bend(
        edge.id,
        edgePos,
        previousIndex,
        { top: positions.startTop, left: positions.startLeft },
        {
            top: evt.clientY,
            left: evt.clientX,
        },
        fc as any,
        conn
    );
}

export const bindConnEvents = (conn: Connection): void => {
    (conn as any).bind("mouseover", (c: Connection) => {
        (conn as any).setPaintStyle({ stroke: "blue", strokeWidth: 3 })
    });
    (conn as any).bind("mouseout", (c: Connection) => {
        (conn as any).setPaintStyle({ stroke: currentColorScheme().flowchart.lineStroke, strokeWidth: 3 })
    });

}
